/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.jr.wx.video.downloadagent.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;

/**
 *
 * @author G
 */
public class FileTools {

    private static Logger logger = Logger.getLogger(FileTools.class);

    public static List<File> getFiles(File fileDir, String fileType) {
        List<File> lfile = new ArrayList<File>();
        File[] fs = fileDir.listFiles();
        for (File f : fs) {
            if (f.isFile()) {
                if (fileType
                        .equals(f.getName().substring(
                                        f.getName().lastIndexOf(".") + 1,
                                        f.getName().length()))) {
                    lfile.add(f);
                }
            } else {
                List<File> ftemps = getFiles(f, fileType);
                lfile.addAll(ftemps);
            }
        }
        return lfile;
    }

    /**
     * 读取数据
     *
     * @param filename 全路径文件名
     * @return sql文件内容链表
     */
    public static List<String> readData(String filename) {
        List<String> list = new ArrayList<String>();
        try {
            FileReader read = new FileReader(filename);
            BufferedReader br = new BufferedReader(read);
            String row = "";
            while ((row = br.readLine()) != null) {
                list.add(row);
            }
        } catch (FileNotFoundException e) {
            logger.error("The file not exists." + filename);

        } catch (IOException e) {
            logger.error("read data error." + filename);
        }
        return list;
    }

    /**
     * 读取数据
     *
     * @param filename 全路径文件名
     * @return 文件内容
     */
    public static String readFile(String filename) {
        StringBuffer sb = new StringBuffer();
        try {
            FileReader read = new FileReader(filename);
            BufferedReader br = new BufferedReader(read);
            String row = "";
            while ((row = br.readLine()) != null) {
                sb.append(row);
            }
        } catch (FileNotFoundException e) {
            logger.error("The file not exists." + filename);

        } catch (IOException e) {
            logger.error("read data error." + filename);

        }
        return sb.toString();
    }

    public static void moveFileToNewPath(String filename, String localpath, String newFilePath) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        String currenttime = sdf.format(new Date());
        if (newFilePath.endsWith("/")) {
            newFilePath = newFilePath + currenttime;
        } else {
            newFilePath = newFilePath + "/" + currenttime;
        }
        File fnewpath = new File(newFilePath);
        //判断文件夹是否存在 
        if (!fnewpath.exists()) {
            fnewpath.mkdirs();
        }

        try {
            File oldFile = new File(localpath + "/" + filename + "");
            File oldOkFile = new File(localpath + "/" + filename + ".ok");

            File fnew = new File(newFilePath + "/" + filename + "");
            File foknew = new File(newFilePath + "/" + filename + ".ok");
            boolean renameTo = oldFile.renameTo(fnew);
            if (!renameTo) {
                logger.info("move file return false " + filename);
            }
            logger.debug(renameTo);
            boolean renameTo1 = oldOkFile.renameTo(foknew);
            if (!renameTo1) {
                logger.info("move file return false " + filename + ".ok");
            }
            logger.debug(renameTo1);
        } catch (Exception e) {
            logger.error("move the file failed,cause " + e.getMessage(), e);
        }

    }

    public void moveFileToNewPath(String filename, String localpath) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        String currenttime = sdf.format(new Date());
        String newFilePath = localpath + "/success/" + currenttime;
        File fnewpath = new File(newFilePath);
        //判断文件夹是否存在 
        if (!fnewpath.exists()) {
            fnewpath.mkdirs();
        }

        try {
            File oldFile = new File(localpath + "/" + filename + "");
            File oldOkFile = new File(localpath + "/" + filename + ".ok");

            File fnew = new File(newFilePath + "/" + filename + "");
            File foknew = new File(newFilePath + "/" + filename + ".ok");
            boolean renameTo = oldFile.renameTo(fnew);
            if (!renameTo) {
                logger.info("move file return false " + filename + " and retry.");
                oldFile.renameTo(fnew);
            }
            logger.debug(renameTo);
            boolean renameTo1 = oldOkFile.renameTo(foknew);
            if (!renameTo1) {
                logger.info("move file return false " + filename + ".ok and retry.");
                oldOkFile.renameTo(foknew);
            }
            logger.debug(renameTo1);
        } catch (Exception e) {
            logger.error("move the file failed,cause " + e.getMessage(), e);
        }

    }

    public static void moveUserFileToNewPath(String file, String newDir) {
        //文件原地址 
        File oldFile = new File(file);
        File oldFileSig = new File(file + ".sig");

        File fnewpath = new File(newDir);
        //判断文件夹是否存在 
        if (!fnewpath.exists()) {
            fnewpath.mkdirs();
        }
        //将文件移到新文件夹里 
        Calendar c = Calendar.getInstance();
        String strdateString = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DATE);
        File fnew = new File(newDir + File.separator + oldFile.getName() + strdateString);
        File fnewSig = new File(newDir + File.separator + oldFileSig.getName().split(".sig")[0] + strdateString + ".sig");
        oldFile.renameTo(fnew);
        oldFileSig.renameTo(fnewSig);
    }

    /**
     *
     * @param url,通过url判断文件的后缀名是什么，
     * @return
     */
    public static String suffix(String url) {
        String suffixestr = ".m4a|.avi|.mpeg|.3gp|.mp3|.mp4|.wav|.jpeg|.gif|.jpg|.png|.apk|.exe|.pdf|.rar|.zip|.docx|.doc";
        String suffix = null;
        try {

//            String suffixestr = RuntimeEnv.getParam(RuntimeEnv.suffixestr) + "";
            Pattern pat = Pattern.compile(suffixestr);
            Matcher d = pat.matcher(url);
            //注意d.find()只能用一次，否则将查找不到
//            System.out.println("find "+d.find()+","+d.group());
            if (d.find()) {
                suffix = d.group();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return suffix;
    }

//    public static void main(String[] args) {
//        File oldFile = null;
//        oldFile = new File("C:\\Users\\Administrator\\Desktop\\test\\1477988377325");
////        File fnew = new File("C:\\Users\\Administrator\\Desktop\\test\\success\\1477988377325");
////        oldFile.renameTo(fnew);
//
//        moveFileToNewPath(oldFile, "C:\\Users\\Administrator\\Desktop\\test\\success\\");
//
//    }
}
